package com.example.jiaoyidui.component;

import com.example.jiaoyidui.entity.ApiRequestParam;
import com.example.jiaoyidui.entity.excel.ResponseExcel;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.net.SocketTimeoutException;
import java.time.LocalTime;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class Crawler implements Callable<ResponseExcel> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    private BigDecimal amount;
    private String exchange;
    private ApiRequestParam param;
    private ResponseExcel responseExcel;
    private CountDownLatch begin;

    public Crawler(Integer amount, String exchange, ApiRequestParam param, ResponseExcel responseExcel, CountDownLatch begin) {
        //this.amount = amount;
        this.amount = new BigDecimal(amount).divide(new BigDecimal(param.getBaseUnitPrice()), 2, BigDecimal.ROUND_HALF_UP);
        this.exchange = exchange;
        this.param = param;
        this.responseExcel = responseExcel;
        this.begin = begin;
    }

    @Override
    public ResponseExcel call() throws InterruptedException {
        begin.await();
        // 拼接完整地址
        String url = SystemProperties.BASE_API +
                "?exChange=" + exchange
                + "&chainId=" + param.getChainId()
                + "&inTokenSymbol=" + param.getInTokenSymbol()
                + "&inTokenAddress=" + param.getInTokenAddress()
                + "&outTokenSymbol=" + param.getOutTokenSymbol()
                + "&outTokenAddress=" + param.getOutTokenAddress()
                + "&amount=" + amount
                //+ "&gasPrice=" + ("openoceanv2".equals(exchange) ? 81 : param.getGasPrice())
                + "&gasPrice=" + param.getGasPrice()
                + "&slippage=100";
        log.info("url " + url);
        String json = "";
        try {
            String time = LocalTime.now().toString();
            Document document = Jsoup.connect(url).timeout(120000).ignoreContentType(true).get();
            String time1 = LocalTime.now().toString();
            json = document.body().text();
            Map<String, Object> map = objectMapper.readValue(json, Map.class);
            map = (LinkedHashMap<String, Object>) map.get("data");
            String outAmount = (String) map.get("outAmount");
            String transCost = (String) map.get("transCost");

            String inUsd = String.valueOf(((Map) map.get("inToken")).get("inUsd"));
            String outAmountUsd = (String) ((Map) map.get("outToken")).get("outUsd");
            String transCostUsd = (String) map.get("transUsd");


            // 控制台打印看下
            log.info("time " + time);
            log.info("chainId " + param.getChainId());
            log.info("amount " + amount);
            log.info("transPair " + param.getTransPair());
            log.info("exchange " + exchange);
            log.info("inUsd " + inUsd);
            log.info("outAmount " + outAmount);
            log.info("transCost " + transCost);
            log.info("----------------------------------------------------");

//             "openoceanv1", "openoceanv2", "oneinch", "paraswap", "matcha"，填到对应的单元格中
            switch (exchange) {
                case "openoceanv1":
                    responseExcel.setOpenOceanV1Price(outAmount);
                    responseExcel.setOpenOceanV1Gas(transCost);
                    responseExcel.setOpenOceanV1PriceUsd(outAmountUsd);
                    responseExcel.setOpenOceanV1GasUsd(transCostUsd);
                    responseExcel.setOpenOceanV1InUsd(inUsd);
                    responseExcel.setOpenOceanV1Time(time+" "+time1);
                    break;
                case "openoceanv2":
                    responseExcel.setOpenOceanV2Price(outAmount);
                    responseExcel.setOpenOceanV2Gas(transCost);
                    responseExcel.setOpenOceanV2PriceUsd(outAmountUsd);
                    responseExcel.setOpenOceanV2GasUsd(transCostUsd);
                    responseExcel.setOpenOceanV2InUsd(inUsd);
                    responseExcel.setOpenOceanV2Time(time+" "+time1);
                    break;
                case "1inch":
                    responseExcel.setLinchPrice(outAmount);
                    responseExcel.setLinchGas(transCost);
                    responseExcel.setLinchPriceUsd(outAmountUsd);
                    responseExcel.setLinchGasUsd(transCostUsd);
                    responseExcel.setLinchInUsd(inUsd);
                    responseExcel.setLinchTime(time+" "+time1);
                    break;
                case "paraswap":
                    responseExcel.setParaswapPrice(outAmount);
                    responseExcel.setParaswapPriceGas(transCost);
                    responseExcel.setParaswapPriceUsd(outAmountUsd);
                    responseExcel.setParaswapPriceGasUsd(transCostUsd);
                    responseExcel.setParaswapInUsd(inUsd);
                    responseExcel.setParaswapTime(time+" "+time1);
                    break;
                case "matcha":
                    responseExcel.setMechaPrice(outAmount);
                    responseExcel.setMechaPriceGas(transCost);
                    responseExcel.setMechaPriceUsd(outAmountUsd);
                    responseExcel.setMechaPriceGasUsd(transCostUsd);
                    responseExcel.setMechaInUsd(inUsd);
                    responseExcel.setMechaTime(time+" "+time1);
                    break;
                default:
                    break;
            }
        } catch (JsonParseException e) {
            log.error("url：{}", url);
            log.error("JSON解析失败：{}", json);
        } catch (SocketTimeoutException e) {
            log.error("url：{}", url);
            log.error("连接超时：{}", e.getMessage());
        } catch (HttpStatusException e) {
            log.error("url：{}", url);
            log.error("http响应错误：{}", e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseExcel;
    }
}
